package com.xyd.wechat.controller;

import com.xyd.wechat.common.Constant;
import com.xyd.wechat.tools.VerificationTool;
import com.xyd.wechat.tools.WechatHandlerTool;
import com.xyd.wechat.vo.TokenVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;


/**
 * 微信公众号服务接口
 */
@Slf4j
@RestController
public class WechatController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private VerificationTool verificationTool;

    @Autowired
    private WechatHandlerTool wechatHandlerTool;

    @RequestMapping(value = {Constant.BASE_PATH + "/wx/api"}, method = {RequestMethod.POST, RequestMethod.GET})
    public Object wxApi(HttpServletRequest request) {
        try {
            if (request.getMethod().equals(RequestMethod.GET.name())) {
                // 处理token验证
                TokenVo tokenVo = new TokenVo();
                tokenVo.setSignature(request.getParameter("signature"));
                tokenVo.setTimestamp(request.getParameter("timestamp"));
                tokenVo.setNonce(request.getParameter("nonce"));
                tokenVo.setEchostr(request.getParameter("echostr"));
                return verificationTool.signature(tokenVo);
            }

            if (request.getMethod().equals(RequestMethod.POST.name())) {
                // 当你用微信给平台发送信息时就会到这里
                // 获取微信XML消息体
                // TODO 消息类型 , 消息类型  种类很多，可以优化
                String wxMsgXml = IOUtils.toString(request.getInputStream(), StandardCharsets.UTF_8);
                return wechatHandlerTool.autoReplyByRobot(wxMsgXml);
            }

            // 错误的请求类型
            logger.error("错误的请求类型:{}", request.getMethod());
            return null;
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }
}
